﻿using AutoMapper;
using Ezpay.ServiceContract;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Ezpay.UI.ViewModels
{
    class EditCustomerViewModel : BaseViewModel, INavigationAware
    {
        private IRegionManager _regionManager;
        private UpdateCustomerRequest _customer;
        public UpdateCustomerRequest Customer
        {
            get { return _customer; }
            private set
            {
                _customer = value;
                RaisePropertyChanged(() => Customer);
            }
        }

        public ICommand CancelCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public EditCustomerViewModel(IRegionManager regionManager, IEzpayService ezPayService)
        {
            _ezpayService = ezPayService;
            _regionManager = regionManager;
            CancelCommand = new RelayCommand(Cancel);
            SaveCommand = new RelayCommand(Save);
        }

        private bool _isBusy;
        private IEzpayService _ezpayService;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged(() => IsBusy);
            }
        }

        private async void Save()
        {
            IsBusy = true;

            await Task.Factory.StartNew(() =>
            {
                _ezpayService.UpdateCustomer(Customer);
            });

            IsBusy = false;
        }
        private void Cancel()
        {
            var query = new UriQuery();
            query.Add("ID", Customer.CustomerID);

            _regionManager.ShowInMain("CustomerViewModel" + query.ToString());
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return navigationContext.Parameters["ID"] == Customer.CustomerID;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            if (IsNavigationTarget(navigationContext))
                return;

            navigationContext.NavigationService.Region.Remove(this);
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            LoadCustomer(navigationContext.Parameters["ID"]);
        }

        private async void LoadCustomer(string id)
        {
            IsBusy = true;
            var customer = await Task.Factory.StartNew(() =>
            {
                return _ezpayService.GetCustomer(new GetCustomerRequest() { CustomerID = id });
            });
            Customer = Mapper.Map<UpdateCustomerRequest>(customer);
            IsBusy = false;
        }
    }
}
